import cv2
import serial
import datetime
import json

# Setup serial connection
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)  # Update with your port and baud rate

# Video capture settings
video_source = 0  # Adjust this depending on your camera setup
frame_rate = 24  # Frames per second
resolution = (640, 480)  # Set this according to your camera's capabilities

# Initialize video capture
cap = cv2.VideoCapture(video_source)

# JSON Data setup
data_records = []

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        # Generate timestamp for the frame
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S%f")
        
        # Read motor speed
        if ser.in_waiting > 0:
            motor_speed = ser.readline().decode().strip()
            
        else:
            motor_speed = 'No Data'
        
        # Save the frame to a jpg file
        filename = f"frame_{timestamp}.jpg"
        cv2.imwrite(filename, frame)
        
        # Record data
        data = {
            "timestamp": timestamp,
            "frame": filename,
            "motor_speed": motor_speed
        }
        data_records.append(data)
        
        # Optionally, display the frame
        cv2.imshow('Frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Save metadata to JSON file after recording is done
with open('data.json', 'w') as f:
    json.dump(data_records, f, indent=4)

# Cleanup
cap.release()
cv2.destroyAllWindows()
ser.close()
